<template>
  <div class="draggable-header" @mousedown="handleMouseDown">
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
import { onUnmounted, ref } from 'vue'
import { useSystemStore } from '@/pinia/system'
const store = useSystemStore()

const props = defineProps({
  prohibited: {
    type: Boolean,
    default: false
  },
  sizable: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['dragEnd'])

const isDragging = ref(false)
const currentWindowId = ref(-1)
const startPos = ref({ x: 0, y: 0 })
const dragThreshold = 5

// 确保主进程通信可用
const electronAPI = window.electron || {
  ipcRenderer: {
    invoke: () => Promise.resolve(-1),
    send: () => {}
  }
}

const handleMouseMove = (e: MouseEvent) => {
  if (!isDragging.value) return

  const dx = Math.abs(e.screenX - startPos.value.x)
  const dy = Math.abs(e.screenY - startPos.value.y)

  if (dx > dragThreshold || dy > dragThreshold) {
    electronAPI.ipcRenderer.send('window-drag:move', currentWindowId.value, e.screenX, e.screenY)
  }
}

const handleMouseUp = async () => {
  if (!isDragging.value) return

  isDragging.value = false
  electronAPI.ipcRenderer.send('window-drag:end', currentWindowId.value, props.sizable)

  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)

  const position = await electronAPI.ipcRenderer.invoke('get-location-information')
  if (position && position.length === 2) {
    const [x, y] = position
    if (x !== store.gPosition[0] || y !== store.gPosition[1]) {
      store.editstore({ gPosition: position })

      emit('dragEnd', true)
    } else {

      emit('dragEnd', false)
    }
  }
}

const handleMouseDown = async (e: MouseEvent) => {
  if (props.prohibited || e.button !== 0) return

  isDragging.value = true
  startPos.value = { x: e.screenX, y: e.screenY }

  const windowId = await electronAPI.ipcRenderer.invoke('window-drag:get-window-id')
  if (windowId === -1) return
  currentWindowId.value = windowId

  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp, { once: true })

  electronAPI.ipcRenderer.send('window-drag:start', windowId, e.screenX, e.screenY)
}

onUnmounted(() => {
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)

  if (isDragging.value && currentWindowId.value !== -1) {
    electronAPI.ipcRenderer.send('window-drag:end', currentWindowId.value, props.sizable)
  }
})
</script>

<style scoped>
.draggable-header {
  position: relative;
  -webkit-app-region: no-drag; /* 允许拖拽区域 */
  user-select: none;
  cursor: default;
}

/* 确保没有其他样式覆盖拖拽行为 */
.draggable-header * {
  -webkit-app-region: no-drag;
   /* 防止子元素拦截事件 */
  /* pointer-events: none; */
}
</style>
